package org.uim.cricket.storage.queries;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.uim.cricket.entities.FullPlayer;
import org.uim.cricket.entities.match.CricketMatch;

public class PlayerQueryGenerator extends QueryGenerator {

	private FullPlayer player = null;
	
	public PlayerQueryGenerator(CricketMatch theMatch, FullPlayer player) {
		super(theMatch);
		this.player = player;
	}

	@Override
	public String generateQuery() throws Exception {
		StringBuilder query = new StringBuilder("CALL sp_Insert_Player(");
		query.append(this.player.getId()).append(",");
		this.appendQuery(query, encodeSQL(this.player.getDisplayName()), 64, false);
		this.appendQuery(query, encodeSQL(this.player.getShortName()), 128, false);
		this.appendQuery(query, encodeSQL(this.player.getFullName()), 256, false);
		this.appendQuery(query, encodeSQL(this.player.getCountry()), 128, false);
		if (this.player.getBirthdate() != null) {
			query.append("'").append(this.player.getBirthdate().get(Calendar.YEAR)).append("-");
			query.append(this.player.getBirthdate().get(Calendar.MONTH) + 1).append("-");
			query.append(this.player.getBirthdate().get(Calendar.DATE)).append("'");
		} else {
			query.append("NULL");
		}
		query.append(");\n");
		
		if (this.player.getOtherValues()!=null && this.player.getOtherValues().size() > 0) {
			query.append(this.insertAttributes(this.player.getOtherValues()));
		}
		if (this.player.getCountries() != null && this.player.getCountries().size() > 0) {
			query.append(this.insertTeams(this.player.getCountries()));
		}
		
		return query.toString();
	}

	private String insertAttributes(Map<String, String> attributes) throws Exception {
		StringBuilder allq = new StringBuilder();
		for (String key : attributes.keySet()) {
			String value = attributes.get(key);
			
			StringBuilder query = new StringBuilder("CALL sp_Insert_PlayerDetail(");
			query.append(this.player.getId()).append(",");
			this.appendQuery(query, encodeSQL(key), 64, false);
			this.appendQuery(query, encodeSQL(value), 256, false, false);
			query.append(");");
			
			allq.append(query.toString()).append("\n");
		}
		return allq.toString();
	}
	
	private String insertTeams(List<String> teams) throws Exception {
		StringBuilder allq = new StringBuilder();
		for (String team : teams) {
			StringBuilder query = new StringBuilder("CALL sp_Insert_PlayerDetail(");
			query.append(this.player.getId()).append(",");
			this.appendQuery(query, "Major teams", 20, false);
			this.appendQuery(query, encodeSQL(team), 128, false, false);
			query.append(");");
			
			allq.append(query.toString()).append("\n");
		}
		return allq.toString();
	}
	
	public void setPlayer(FullPlayer player) {
		this.player = player;
	}
	
	public FullPlayer getPlayer() {
		return player;
	}
	
}
